// pages/login/login.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userNameValue:'',
    passwordValue:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('login', "onLoad");
    var username = wx.getStorageSync("username");
    if (wx.getStorageSync("username")!=null&&username!=''){
      this.setData({
        userNameValue:username
      })
    }
  },
  inputUserName:function(e){
    console.log("***", e.detail.value)
    this.setData({
      userNameValue:e.detail.value,
    })
    console.log("***", this.data.userNameValue)
  },
  inputPassword: function(e){
    this.setData({
      passwordValue:e.detail.value
    })
  },
  /**
   * 用户登录操作
   */
  userLogin() {
    let _this = this;
    if (this.data.userNameValue == ''){
      wx.showToast({
        title: '账号不能为空',
        icon: "none"
      })
      return;
    } else if (this.data.passwordValue == ''){
      wx.showToast({
        title: '请输入密码',
        icon: "none"
      })
      return;
    }else{
      
      
      //请求登录接口
      var md5 = require("../../utils/md5.js")
      let md5pwd = md5(this.data.passwordValue);
      wx.request({
        url: app.globalData.ipPort +'/front/auth/login', 
        data: {
          password: md5pwd,
          userName: _this.data.userNameValue
        },
        method:'post',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if(res.data.code==200){
            console.log("用户名", res.data.data.userType)
            console.log("用户类型", res.data.data.userName)
            console.log("用户ID", res.data.data.userId)
            wx.setStorageSync("username",res.data.data.userName); 
            app.globalData.userType = res.data.data.userType;
            app.globalData.userName = res.data.data.userName;
            app.globalData.userId = res.data.data.userId;
            console.log("sessionId=" + res.data.data.sessionId)
            app.globalData.header.Cookie = 'JSESSIONID=' + res.data.data.sessionId;
            _this.loginSuccess();
          }else if(res.data.code ==500){
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          }
          
        }
      })

      
    
    }

    

  },
  /**
   * 登录成功操作
   */
  loginSuccess() {
    
    //登录成功，根据用户信息跳转到不太的页面，当前跳转到首页
    // wx.redirectTo({
    //   url: "/pages/common/pages/index/index"
    // })

     if (app.globalData.userType == "user"){
       //普通账号
       wx.redirectTo({
         url: "/pages/common/pages/index/index"
       })
     }else{
       //管理员账号
       wx.redirectTo({
         url: "/pages/admin/pages/index/index"
       })
     }


  },
})